package com.bottle.android_mvi.ui.view

import android.os.Bundle
import android.view.View
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.viewbinding.ViewBinding
import com.bottle.android_mvi.domain.viewmodel.BaseMVIViewModel
import com.bottle.lib_core.ui.view.BaseBingFragment

/**
 * 基础Fragment类，提供ViewBinding和ViewModel的绑定和处理机制
 * @param VB ViewBinding类型
 * @param VM 基础ViewModel类型，支持泛型参数
 */
abstract class BaseMVIFragment<VB : ViewBinding, VM : BaseMVIViewModel<*, *, *>> : BaseBingFragment<VB>()  {
    // 抽象属性，用于获取ViewModel实例
    protected abstract val vm: VM

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // 观察ViewModel的状态或事件
        observeStateOrEvent(vm)
        // 绑定生命周期，确保LifecycleObserver正确工作
        bindingLifecycle(viewLifecycleOwner.lifecycle)
    }

    // 抽象方法，用于观察ViewModel的状态或事件
    abstract fun observeStateOrEvent(viewModel: VM)

    /**
     * 绑定生命周期观察者
     * @param lifecycle Fragment的生命周期
     */
    private fun bindingLifecycle(lifecycle: Lifecycle) {
        // BaseRenderer must be public, `getFields()` improve performance
        for (field in this::class.java.fields) {
            val value = field.get(this)
            // 如果字段是LifecycleObserver类型，则添加为生命周期观察者
            if (value is LifecycleObserver) {
                lifecycle.addObserver(value)
            }
        }
    }
}